﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using UnitTests.Framework;
using System.Net.Sockets;

namespace UnitTests.FrameworkTests
{
	internal class TestServerTestClient : TestClientBase<EchoClientHandler>
	{
		public const int TEST_PORT = 54001;

		public TestServerTestClient()
			: base(TEST_PORT)
		{ }

		protected override bool VerifyWelcomeMessage(string message)
		{
			return EchoClientHandler.WELCOME_MESSAGE == message;
		}
	}

	[TestClass]
	public class TestServerTest
	{
		[TestMethod]
		public void TSEchoServerTest()
		{
			using (TestServerTestClient testClient = new TestServerTestClient())
			{
				string testMessage = "Hello, World!";
				testClient.ProcessCommand(testMessage, testMessage, "Server did not echo message correctly");
			}
		}

		[TestMethod]
		public void TSFindClientHandlerTest()
		{
			using (TestServer<EchoClientHandler> testServer = new TestServer<EchoClientHandler>(TestServerTestClient.TEST_PORT))
			{
				using (TcpClient client1 = new TcpClient(), client2 = new TcpClient())
				{
					client1.Connect(System.Net.IPAddress.Loopback, TestServerTestClient.TEST_PORT);
					client2.Connect(System.Net.IPAddress.Loopback, TestServerTestClient.TEST_PORT);

					EchoClientHandler clientHandler1 = testServer.FindClientHandler(client1.Client.LocalEndPoint);
					EchoClientHandler clientHandler2 = testServer.FindClientHandler(client2.Client.LocalEndPoint);

					Assert.IsNotNull(clientHandler1, "First client handler was not found");
					Assert.IsNotNull(clientHandler2, "Second client handler was not found");
					Assert.AreNotSame(clientHandler1, clientHandler2, "Client handlers were the same");
				}
			}
		}
	}
}
